package com.tanhua.dubbo.api;

import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.VideoComment;
import com.tanhua.model.mongo.VideoCommentLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@DubboService
public class VideoCommentLikeApiImpl implements VideoCommentLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean find(Long userId, String commentId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("commentId").is(new ObjectId(commentId)));
        return mongoTemplate.exists(query, VideoCommentLike.class);
    }

    @Override
    public void save(VideoCommentLike videoCommentLike) {
        mongoTemplate.insert(videoCommentLike);
        //修改评论表中的评论点赞数量
        Query query = Query.query(Criteria.where("_id").is(videoCommentLike.getCommentId()));
        VideoComment videoComment = mongoTemplate.findById(videoCommentLike.getCommentId(), VideoComment.class);
        Update update = new Update();
        if (videoComment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("likeCount", 1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        mongoTemplate.findAndModify(query, update, options, VideoComment.class);
    }

    @Override
    public void delete(Long userId, String commentId) {
        Query query = Query.query(Criteria.where("_id").is(commentId).and("userId").is(userId));
        mongoTemplate.remove(query, VideoCommentLike.class);
        //修改评论表中的评论点赞数量
        Query query1 = Query.query(Criteria.where("_id").is(commentId));
        VideoComment videoComment = mongoTemplate.findById(commentId, VideoComment.class);
        Update update = new Update();
        if (videoComment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("likeCount", -1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        mongoTemplate.findAndModify(query1, update, options, VideoComment.class);
    }
}
